package com.itheima.tlias.aspect;


import com.itheima.tlias.annotation.EmpLogAop;
import com.itheima.tlias.pojo.EmpLog;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.service.EmpLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class EmpLogAspect {
    @Autowired
    EmpLogService empLogService;

    //全类名地址，可以不用创建实例对象指向地址
    @Pointcut("@annotation(com.itheima.tlias.annotation.EmpLogAop)")
    public void empLogPointcut() {
    }

    @AfterReturning(pointcut = "empLogPointcut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        Result result1 = (Result) result;
        // 判断被切入的方法是新增还是修改
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();
        String info = "code:" + result1.getCode() + "\nmsg:" + result1.getMsg()+"\noperate:"+method.getName();
        EmpLog empLog = com.itheima.tlias.pojo.EmpLog.builder()
                .operateTime(LocalDateTime.now())
                .info(info)
                .build();
        empLogService.insert(empLog);
    }

}
